// pages/discipline/history.js
Page({
  data: {
    sleepRecords: [],
    wakeRecords: [],
    currentTab: 'sleep', // 'sleep' 或 'wake'
    loading: false,
    // 统计数据
    stats: {
      totalSleep: 0,
      totalWake: 0,
      onTimeSleep: 0,
      onTimeWake: 0
    }
  },

  onLoad: function () {
    this.loadHistoryData();
  },

  onShow: function () {
    this.loadHistoryData();
  },

  // 加载历史数据
  loadHistoryData: function () {
    this.setData({ loading: true });
    
    const records = wx.getStorageSync('sleepRecords') || [];
    
    // 按日期排序，最新的在前面
    const sortedRecords = records.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    // 分离早睡和早起记录
    const sleepRecords = sortedRecords.filter(record => record.type === 'sleep');
    const wakeRecords = sortedRecords.filter(record => record.type === 'wake');
    
    // 计算统计数据
    const stats = {
      totalSleep: sleepRecords.length,
      totalWake: wakeRecords.length,
      onTimeSleep: sleepRecords.filter(record => record.isOnTime).length,
      onTimeWake: wakeRecords.filter(record => record.isOnTime).length
    };
    
    this.setData({
      sleepRecords: sleepRecords,
      wakeRecords: wakeRecords,
      stats: stats,
      loading: false
    });
  },

  // 切换标签页
  switchTab: function (e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
  },

  // 删除记录
  deleteRecord: function (e) {
    const recordId = e.currentTarget.dataset.id;
    const recordType = e.currentTarget.dataset.type;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条记录吗？',
      success: (res) => {
        if (res.confirm) {
          this.confirmDelete(recordId, recordType);
        }
      }
    });
  },

  // 确认删除记录
  confirmDelete: function (recordId, recordType) {
    let records = wx.getStorageSync('sleepRecords') || [];
    
    // 根据时间戳删除记录
    records = records.filter(record => record.timestamp !== recordId);
    
    wx.setStorageSync('sleepRecords', records);
    
    wx.showToast({
      title: '删除成功',
      icon: 'success',
      duration: 2000
    });
    
    // 重新加载数据
    this.loadHistoryData();
  },

  // 清空所有记录
  clearAllRecords: function () {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有记录吗？此操作不可恢复！',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('sleepRecords');
          
          this.setData({
            sleepRecords: [],
            wakeRecords: [],
            stats: {
              totalSleep: 0,
              totalWake: 0,
              onTimeSleep: 0,
              onTimeWake: 0
            }
          });
          
          wx.showToast({
            title: '已清空所有记录',
            icon: 'success',
            duration: 2000
          });
        }
      }
    });
  },

  // 导出数据
  exportData: function () {
    const records = wx.getStorageSync('sleepRecords') || [];
    
    if (records.length === 0) {
      wx.showToast({
        title: '没有数据可导出',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 格式化数据为可读文本
    let exportText = '人生管理系统 - 自律记录\n';
    exportText += '导出时间：' + new Date().toLocaleString() + '\n\n';
    
    records.forEach((record, index) => {
      exportText += `${index + 1}. ${record.date} ${record.time}\n`;
      exportText += `   类型：${record.type === 'sleep' ? '早睡' : '早起'}\n`;
      exportText += `   状态：${record.isOnTime ? '按时' : '延迟'}\n\n`;
    });
    
    // 复制到剪贴板
    wx.setClipboardData({
      data: exportText,
      success: () => {
        wx.showToast({
          title: '数据已复制到剪贴板',
          icon: 'success',
          duration: 2000
        });
      }
    });
  }
});
